package com.jyy.prefabricated.service;

import com.jyy.prefabricated.dto.BatchDto;
import com.jyy.prefabricated.dto.ExamApplyDto;
import com.jyy.prefabricated.entity.*;
import com.jyy.prefabricated.enums.ApplyStatusEnum;
import com.jyy.prefabricated.exception.CustomException;
import com.jyy.prefabricated.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Transactional
@Service
public class ExamApplyService {

    @Resource
    private ExamApplyMapper examApplyMapper;

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private ExamApplyStudentMapper applyStudentMapper;

    @Resource
    private ExamMapper examMapper;

    @Resource
    private ProjectInfoMapper projectInfoMapper;

    @Resource
    private ExamPointsMapper pointsMapper;

    @Resource
    private StudentProjectMapper studentProjectMapper;

    @Resource
    private TrainingOrganizationMapper trainingOrganizationMapper;

    /**
     * 新增
     *
     * @param dto
     * @return
     */
    public Integer insert(ExamApplyDto dto) {
        ExamApply examApply = new ExamApply();
        BeanUtils.copyProperties(dto, examApply);
        if (dto.getTrainingOrganizationId() != null) {
            //examApply.setStatus(ApplyStatusEnum.WAIT.getValue());
            examApply.setStatus(ApplyStatusEnum.SUCCESS.getValue());
        } else {
            examApply.setStatus(ApplyStatusEnum.SUCCESS.getValue());
        }
        Exam exam = examMapper.selectByPrimaryKey(dto.getExamId());
        ProjectInfo projectInfo = projectInfoMapper.selectByPrimaryKey(exam.getProjectId());
        ExamPoints point = pointsMapper.selectByPrimaryKey(exam.getPointId());
        if (exam != null) {
            examApply.setExamName(exam.getName());
        }
        if (projectInfo != null) {
            examApply.setProjectId(projectInfo.getId());
            examApply.setProjectName(projectInfo.getName());

        }
        if (point != null) {
            examApply.setPointId(point.getId());
            examApply.setPointAddress(point.getAddress());
            examApply.setPointName(point.getName());
        }

        examApplyMapper.insert(examApply);
        saveApplyId2Student(dto, examApply.getId());

        //批量更新分配状态
        studentProjectMapper.batchUpdateStatus(dto.getStudentIds(), exam.getProjectId());
        return examApply.getId();
    }

    /**
     * 保存申请和学员的绑定信息
     *
     * @param dto
     * @param id
     */
    public void saveApplyId2Student(ExamApplyDto dto, Integer id) {
        if (dto.getStudentIds().size() > 0) {
            List<ExamApplyStudent> applyStudents = new ArrayList<>();
            for (Integer studentId : dto.getStudentIds()) {
                ExamApplyStudent applyStudent = new ExamApplyStudent();
                applyStudent.setApplyId(id);
                applyStudent.setStudentId(studentId);
                applyStudents.add(applyStudent);
            }
            applyStudentMapper.batchInsert(applyStudents);
        }
    }

    /**
     * 更新
     *
     * @param dto
     * @return
     */
    public int update(ExamApplyDto dto) {
        if (dto.getId() == null) {
            throw new CustomException("参数id不能为空");
        }
        ExamApply examApply = new ExamApply();
        BeanUtils.copyProperties(dto, examApply);
        applyStudentMapper.deleteByApplyId(dto.getId());
        saveApplyId2Student(dto, dto.getId());
        return examApplyMapper.updateByPrimaryKeySelective(examApply);
    }

    /**
     * 批量更新状态
     *
     * @param dto
     * @return
     */
    public int batchUpdateStatus(BatchDto dto) {
        if (dto.getIds().size() == 0) {
            throw new CustomException("参数id不能为空");
        }
        return examApplyMapper.batchUpdateStatus(dto.getIds(), dto.getStatus());
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    public int delete(Integer id) {
        return examApplyMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public ExamApply selectById(Integer id) {
        return examApplyMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据参数查询列表
     *
     * @param projectId                项目id
     * @param examName                 考试名称
     * @param trainingOrganizationName 机构名称
     * @param pointId                  考核点id
     * @param studentName              学员姓名
     * @param idCard                   学员身份证
     * @param applyStatus              申请状态
     * @param examStatus               考试状态
     * @param applyStartDate           申请开始时间
     * @param applyEndDate             申请结束时间
     * @return
     */
    public List<ExamApply> selectByParams(Integer projectId, String examName, Integer pointId, String trainingOrganizationName, Integer trainingOrganizationId, String studentName, String idCard, Integer applyStatus, Integer examStatus, String applyStartDate, String applyEndDate) {
        return examApplyMapper.selectByParams(projectId, examName, pointId, trainingOrganizationName, trainingOrganizationId, studentName, idCard, applyStatus, examStatus, applyStartDate, applyEndDate);
    }

    /**
     * 查询机构可以申请考试的学员列表
     *
     * @param trainingOrganizationId 机构id
     * @param examId                 考试id
     * @param projectId              项目id
     * @param name                   学员名称
     * @param idCard                 学员身份证号
     * @param trainingOrganizationId 培训机构
     * @param allocationStatus       分配状态（0未分配，1已分配）
     * @return
     */
    public List<Student> selectCanApplyStudentByTOIdAndExamId(Integer trainingOrganizationId, Integer examId, Integer projectId, String name, String idCard, Integer allocationStatus) {
        List<Student> studentList = studentMapper.selectCanApplyStudentByTOIdAndExamId(trainingOrganizationId, examId, projectId, name, idCard, allocationStatus);
        for (Student student : studentList) {
            if(student.getExamApplyStatus()!=null &&student.getExamApplyStatus()==3){
                student.setAllocationStatus(1);
            }else{
                student.setAllocationStatus(0);
            }
            ProjectInfo projectInfo = projectInfoMapper.selectByPrimaryKey(student.getProjectId());
            if (projectInfo != null) {
                student.setProjectName(projectInfo.getName());
            }
            TrainingOrganization trainingOrganization = trainingOrganizationMapper.selectByPrimaryKey(student.getTrainingOrganizationId());
            if (trainingOrganization != null) {
                student.setTrainingOrganizationName(trainingOrganization.getName());
            }
        }
        return studentList;
    }
}
